package com.wcpdoc.survey.survey.dao.impl;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.wcpdoc.survey.core.dao.impl.BaseDaoImpl;
import com.wcpdoc.survey.core.entity.PageIn;
import com.wcpdoc.survey.core.entity.PageOut;
import com.wcpdoc.survey.core.util.SqlUtil;
import com.wcpdoc.survey.core.util.SqlUtil.Order;
import com.wcpdoc.survey.core.util.ValidateUtil;
import com.wcpdoc.survey.survey.dao.SurveyTypeDao;
import com.wcpdoc.survey.survey.entity.SurveyType;

/**
 * 调查分类数据访问层实现
 * 
 * v1.0 zhanghc 2017-06-28 21:34:41
 */
@Repository
public class SurveyTypeDaoImpl extends BaseDaoImpl<SurveyType> implements SurveyTypeDao {

	@Override
	public PageOut getListpage(PageIn pageIn) {
		String sql = "SELECT SURVEY_TYPE.ID, SURVEY_TYPE.NAME, SURVEY_TYPE.PARENT_SUB, "
				+ "SURVEY_TYPE.PARENT_ID, SURVEY_TYPE.NO, PARENT_SURVEY_TYPE.NAME AS PARENT_NAME "
				+ "FROM SV_SURVEY_TYPE SURVEY_TYPE "
				+ "LEFT JOIN SV_SURVEY_TYPE PARENT_SURVEY_TYPE ON SURVEY_TYPE.PARENT_ID = PARENT_SURVEY_TYPE.ID";
		SqlUtil sqlUtil = new SqlUtil(sql);
		sqlUtil.addWhere(ValidateUtil.isValid(pageIn.getOne()) && !"1".equals(pageIn.getOne()), "SURVEY_TYPE.PARENT_ID = ?", pageIn.getOne())//如果查询的是根目录，则查询所有。否则查询选中机构的子机构
				.addWhere(ValidateUtil.isValid(pageIn.getTwo()), "SURVEY_TYPE.NAME LIKE ?", "%" + pageIn.getTwo() + "%")
				.addWhere("SURVEY_TYPE.STATE = ?", 1)
				.addOrder("SURVEY_TYPE.NO", Order.ASC);
		PageOut pageOut = getListpage(sqlUtil, pageIn);
		return pageOut;
	}

	@Override
	public List<Map<String, Object>> getTreeList() {
		String sql = "SELECT SURVEY_TYPE.ID, SURVEY_TYPE.NAME, SURVEY_TYPE.PARENT_ID, SURVEY_TYPE.PARENT_SUB "
				+ "FROM SV_SURVEY_TYPE SURVEY_TYPE "
				+ "WHERE SURVEY_TYPE.STATE = 1";
		return getList(sql);
	}

	@Override
	public void doMove(Integer sourceId, Integer targetId) {
		SurveyType sourceSurveyType = getEntity(sourceId);
		SurveyType targetSurveyType = getEntity(targetId);
		sourceSurveyType.setParentId(targetId);
		flush();

		String sql = "UPDATE SV_SURVEY_TYPE SURVEY_TYPE" 
				+ "	SET SURVEY_TYPE.PARENT_SUB = REPLACE(SURVEY_TYPE.PARENT_SUB, ?, ?)"
				+ "	WHERE SURVEY_TYPE.PARENT_SUB LIKE ?";
		Object[] params = new Object[] { 
					sourceSurveyType.getParentSub(), 
					targetSurveyType.getParentSub() + sourceSurveyType.getId() + "_",
					sourceSurveyType.getParentSub() + "%" };
		update(sql, params);
	}
	
	@Override
	public List<SurveyType> getAllSubSurveyTypeList(Integer id) {
		String sql = "SELECT * FROM SV_SURVEY_TYPE WHERE PARENT_SUB LIKE ? AND STATE = 1";
		return getList(sql, new Object[]{"%\\_"+id+"\\_%"}, SurveyType.class);
	}
	
	@Override
	public SurveyType getSurveyTypeByName(String name) {
		String sql = "SELECT * FROM SV_SURVEY_TYPE WHERE NAME = ? AND STATE = 1";
		return getUnique(sql, new Object[]{name}, SurveyType.class);
	}
}